package com.lovo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.system.dto.StockDto;
import com.lovo.system.mapper.StockMapper;
import com.lovo.system.service.IStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, StockDto> implements IStockService {

    @Autowired
    StockMapper stockMapper;

    @Override
    public IPage<StockDto> info(int curPage, int pageSize, int startNumber, int endNumber, String name, int type, int priceStatus) {
        QueryWrapper qw = new QueryWrapper();
        if (startNumber>0) {
            qw.ge("stock_number", startNumber);
        }
        if (endNumber>0) {
            qw.le("stock_number", endNumber);
        }
        if (name != null && !name.equals("")) {
            qw.like("stock_name", name);
        }
        if (type==1 || type==2 || type==3 || type==4){
            qw.eq("stock_type",type);
        }
        if (priceStatus==1){
            qw.eq("stock_suggest_price",0);
        }
        return stockMapper.selectPage(new Page<>(curPage, pageSize), qw);
    }

    @Override
    public int selectRepeat(StockDto stockDto) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("code",stockDto.getCode());
        int count = stockMapper.selectCount(qw);
        if (count == 1){
            stockMapper.addStockNumber(stockDto.getCode(),stockDto.getStockNumber());
            return 0;
        }
        return 1;
    }

    @Override
    public StockDto selectByCode(String code) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("code",code);
        return stockMapper.selectOne(qw);
    }

    @Override
    public void insertStock(StockDto stockDto) {
        stockMapper.insert(stockDto);
    }

    @Override
    public StockDto queryOneById(int id) {
        return stockMapper.selectById(id);
    }

    @Override
    public String updatePrice(StockDto stockDto) {
        try {
            stockMapper.updateById(stockDto);
            return "修改成功";
        }catch (Exception e){
            return "修改失败";
        }
    }

    @Override
    public void deleteStock(int id) {
        stockMapper.deleteById(id);
    }

    @Override
    public void changeNumber(String name, int number) {
        stockMapper.reduceStockNumber(name,number);
    }

}
